<template>
  <div class="product-quality-management-table">
    <el-row type="flex" justify="space-between" class="mb_16">
      <div>
        <div class="font-16 font-w-600">{{ $t('common.product.serviceItemsTitle') }}</div>
        <div class="product-quality-management-table-tips">{{ $t('product.productQualityServiceItems.serviceItemsTip') }}</div>
      </div>
      <div>
        <el-button type="primary" icon="el-icon-plus" @click="handleClickNewOrEditServiceItem('new')">{{ $t('common.base.create') }}</el-button>
      </div>
    </el-row>

    <el-table v-table-style ref="tableRef" v-loading="listLoading" header-row-class-name="common-list-table-header__v2" :data="dataList" stripe border>
      <template slot="empty">
        <BaseListForNoData v-show="!listLoading" :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
      </template>
{{ columns }}
      <template v-for="column in columns">
        <el-table-column :key="column.field" show-overflow-tooltip :label="column.displayName" :prop="column.field" :min-width="160">
          <template slot-scope="scope">
            <template v-if="column.fieldName === 'svcSerialNumber'">
              {{ getWarrantyServiceItemLabel(scope.row[column.fieldName]) }}
            </template>
            <template v-else-if="column.fieldName === 'svcProjectName'">
              {{ getWarrantyServiceItemLabel(scope.row[column.fieldName]) }} 
              <serviceProjectNameTag v-if="scope.row.system"/>
            </template>
            <template v-else-if="column.fieldName === 'serviceProjectCycle'"> {{ scope.row.timeLimit }}{{ scope.row.timeUnit | cycleFun }} </template>
            <template v-else-if="column.fieldName === 'enabled'"> <el-switch
              :disabled="scope.row.pending"
              @change="changeSwitch(scope.row)"
              :value="Boolean(scope.row.enabled)">
            </el-switch>
            <span style='margin-left:2px;font-size:12px;'>{{ scope.row.enabled == '1' ? '启用' : '禁用' }}</span></template>
            <template v-else>
              {{ $formatFormField(column, scope.row) }}
            </template>
          </template>
        </el-table-column>
      </template>

      <el-table-column :label="$t('common.label.enableOrDisabled')">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.enabled" class="mr_12" @change="changeSwitch(scope.row)" />
          <span style='margin-left:2px;font-size:12px;'>{{ scope.row.enabled ? '启用' : '禁用' }}</span>
        </template>
      </el-table-column>

      <el-table-column fixed="right" :label="$t('common.fields.action.displayName')" width="180">
        <template slot-scope="scope">
          <el-button type="text" size="small" class="pub_btn mr_12" @click="handleClickNewOrEditServiceItem('edit', scope.row)">{{ $t('common.base.edit') }}</el-button>
          <span class="color-danger pub_btn" @click="handleClickDel(scope.row)" v-if="!scope.row.system">{{ $t('common.base.delete') }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="product-quality-management-table-footer" v-if="total">
      <p class="total-count">
        <i18n path="common.base.table.totalCount">
          <span place="count">{{ total }}</span>
        </i18n>
      </p>
      <el-pagination background @current-change="handleCurrentChange" :page-size="paginationInfo.pageSize" :current-page="paginationInfo.pageNum" layout="prev, pager, next" :total="total"> </el-pagination>
    </div>

    <!-- 新建，编辑服务项目 -->
    <service-items-dialog ref="serviceItemRef" :title="dialogTitle" :dialogType="dialogType" @addProductQualityService="addProductQualityService"></service-items-dialog>
  </div>
</template>
<script lang="ts">
import { defineComponent, onMounted, ref, reactive, toRefs } from 'vue';

import { MessageBox } from 'element-ui';
import i18n from '@src/locales';
import { toast } from '@src/util/platform';

import ServiceItemsDialog from './ServiceItemsDialog.vue';
import serviceProjectNameTag from '@src/modules/setting/productV2/productQualityManagement/serviceProjectNameTag.vue';

import { getServiceItemColumn } from '@src/modules/productV2/productWarrantyServiceItem/productWarrantyItemListPage/fields.js';

import { productQualityManageList, productQualityManageListSave, productQualityManageListUpdate, productQualityManageListRemove, productQualityManageListState } from '@src/api/ProductV2Api.js';
import { WarrantyServiceItemLabelEnum } from '@model/enum/LabelEnum'

export default defineComponent({
  name: 'product-quality-management-table',
  components: {
    serviceProjectNameTag,
    ServiceItemsDialog,
  },
  filters: {
    cycleFun(value) {
      const newMap = {
        year: i18n.t('common.base.year'),
        month: i18n.t('common.base.month'),
        day: i18n.t('common.base.day2'),
      };

      return newMap[value] || '';
    },
  },
  setup() {
    const dialogTitle = ref('');
    const dialogType = ref('');

    const serviceItemRef = ref();

    const listLoading = ref(false);

    const columns = [...getServiceItemColumn()];

    let state = reactive({
      paginationInfo: {
        pageNum: 1,
        pageSize: 10,
      },
      dataList: [],
      total: 0,
    });

    // 切换开关
    const changeSwitch = async ({ enabled, id }) => {
      try {
        let ret = await productQualityManageListState({
          id,
          enabled,
        });

        const { success, message, result } = ret || {};

        if (!success) return toast(message, 'error');

        // toast(i18n.t('common.base.tip.modifySuccess'), 'success');
        fetchServiceList();
      } catch (err) {
        console.log('error => changeSwitch', err);
      }
    };

    // 新建, 编辑服务项目
    const handleClickNewOrEditServiceItem = (type, val) => {
      if (type === 'new') {
        dialogTitle.value = i18n.t('product.productQualityServiceItems.newServiceItems');
      } else if (type === 'edit') {
        dialogTitle.value = i18n.t('product.productQualityServiceItems.editServiceItems');
        serviceItemRef.value.form = {
          ...val,
          serialNumber: val.svcSerialNumber,
          projectName: val.svcProjectName,
          remark: val.svcRemark,
        };
      }
      dialogType.value = type;
      serviceItemRef.value.dialogVisible = true;
    };

    // 点击删除
    const handleClickDel = ({ id, svcProjectName }) => {
      MessageBox.confirm(i18n.t('product.productQualityServiceItems.delTips', { projectName: svcProjectName }), i18n.t('common.base.toast'), {
        confirmButtonText: i18n.t('common.base.makeSure'),
        cancelButtonText: i18n.t('common.base.cancel'),
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            productQualityManageListRemove({
              ids: [id],
            }).then(res => {
              instance.confirmButtonLoading = false;

              if (!res.success) {
                return toast(res.message, 'error');
              }

              toast(i18n.t('common.base.tip.deleteSuccess'), 'success');

              done();
              state.paginationInfo.pageNum = 1;
              fetchServiceList();
            });
          } else {
            instance.confirmButtonLoading = false;
            done();
          }
        },
      });
    };

    // 添加服务项目
    const addProductQualityService = (params, type) => {
      const urlMap = {
        new: productQualityManageListSave,
        edit: productQualityManageListUpdate,
      };

      try {
        urlMap[type]({
          ...params,
        }).then(res => {
          let { result, success, message } = res || {};

          if (!success) return toast(message, 'error');

          serviceItemRef.value.handleClickCancel();
          if (type === 'new') {
            state.total = result.total;
            state.paginationInfo.pageNum = result.pageNum;
          }
          fetchServiceList();
        });
      } catch (err) {
        console.log('error => 添加服务项目', err);
      }
    };

    // 获取服务项目列表
    const fetchServiceList = async () => {
      listLoading.value = true;
      try {
        let ret = await productQualityManageList({ ...state.paginationInfo });

        const { success, message, result } = ret || {};

        if (!success) return toast(message, 'error');
        state.dataList = result.list || [];
        state.total = result.total || 0;
      } catch (err) {
        console.log('error => fetchFields', err);
      } finally {
        listLoading.value = false;
      }
    };

    // 切换分页
    const handleCurrentChange = pN => {
      state.paginationInfo.pageNum = pN;
      fetchServiceList();
    };

    // 获取质保服务项目的多语言label
    const getWarrantyServiceItemLabel = (label) => {
      return WarrantyServiceItemLabelEnum[label] || label
    }

    onMounted(() => {
      fetchServiceList();
    });
    return {
      ...toRefs(state),
      dialogType,
      dialogTitle,
      listLoading,
      serviceItemRef,
      columns,
      changeSwitch,
      handleClickNewOrEditServiceItem,
      handleClickDel,
      addProductQualityService,
      handleCurrentChange,
      getWarrantyServiceItemLabel,
    };
  },
});
</script>
<style lang="scss" scoped>
.product-quality-management-table {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  min-height: 100%;
  
  &-tips {
    color: #8c8c8c;
    font-size: 12px;
    margin-top: 4px;
  }

  &-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 12px;
    .total-count {
      font-size: 12px;
      margin: 0;
    }
  }
  .pub_btn {
    cursor: pointer;
    &:hover {
      text-decoration: underline;
    }
  }
}
</style>
